<?php
class SettingsController extends AppController {

	var $name = 'Settings';
	var $helpers = array('Html', 'Form');
	var $uses = array('Setting', 'Backup');
	var $components = array('Backups');

	function beforeFilter() {
		parent::beforeFilter();
		$this->Auth->allow('init');
		$this->set('menu_select', 'settings');
	}

	function index() {
		$this->Setting->recursive = 0;
		$settings = $this->paginate('Setting');
//		pr($settings);
		$this->set('settings', $settings);
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid Setting.', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->set('setting', $this->Setting->read(null, $id));
	}

	function add() {
		if (!empty($this->data)) {
			$this->Setting->create();
			if ($this->Setting->save($this->data)) {
				$this->Session->setFlash(__('The Setting has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Setting could not be saved. Please, try again.', true));
			}
		}
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Setting', true));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->data)) {
			if ($this->Setting->save($this->data)) {
				$this->Session->setFlash(__('The Setting has been saved', true));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The Setting could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Setting->read(null, $id);
		}
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for Setting', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Setting->del($id)) {
			$this->Session->setFlash(__('Setting deleted', true));
			$this->redirect(array('action'=>'index'));
		}
	}

	function init() {
		$count = $this->User->find('count');

		if ($count == 0) {
			$this->redirect(array('controller'=>'users', 'action'=>'register'));
		} else {
			$this->redirect($this->Auth->loginRedirect);
		}

	}

	function backup() {

		$this->User->id = $this->Auth->user('id');

//		pr($this->params);

		$email_confirmed = $this->User->field('email_confirmed')=='1';

		$this->set('email_confirmed', $email_confirmed);

		if (isset($this->params['form']['go'])) {

			$compress = isset($this->params['form']['compress']);

			$email = null;
			if ($email_confirmed) {
				$email = $this->Auth->user('email');
			}

			$this->Backup->create();
			$this->Backup->save(array('Backup'=>array('email'=>$email)));

			if ($this->Backups->backup($compress, $email)) {
				$this->Session->setFlash('Backup successful');
			} else {
				$this->Session->setFlash('Backup failed');
			}
		}


		$backups = $this->Backup->findAll();
		$this->set('backups', $backups);
	}

}
?>